<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item class="smart-query-form-item" label="品牌名称">
        <a-input v-model:value="queryForm.brandName" placeholder="请输入品牌名称" style="width: 160px"/>
      </a-form-item>

      <a-form-item class="smart-query-form-item" label="更新时间">
        <a-space :size="12" direction="vertical">
          <a-range-picker v-model:value="searchDate" :ranges="defaultTimeRanges" @change="dateChange"/>
        </a-space>
      </a-form-item>

      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button type="primary" @click="resetPageNumAjaxQuery">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery">
          <template #icon>
            <ReloadOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card :bordered="false" :hoverable="true" size="small">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button size="small" type="primary" @click="add()">
          <template #icon>
            <PlusOutlined/>
          </template>
          新增品牌
        </a-button>
      </div>
    </a-row>

    <a-table
        :columns="columns"
        :dataSource="tableData"
        :loading="tableLoading"
        :pagination="false"
        :scroll="{ x: 1300 }"
        bordered
        rowKey="enterpriseId"
        size="small"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'icon'">
          <a-image
              :src="text"
              :width="80"
          />
        </template>
        <template v-if="column.dataIndex === 'modelCount'">
          <a @click="goToModelList(record.id)">{{ text }}</a>
        </template>

        <template v-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button type="link" @click="update(record)">编辑</a-button>
            <a-button danger type="link" @click="confirmDelete(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :defaultPageSize="queryForm.pageSize"
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :show-total="(total) => `共${total}条`"
          :total="total"
          show-less-items
          showQuickJumper
          showSizeChanger
          @change="ajaxQuery"
          @showSizeChange="ajaxQuery"
      />
    </div>
  </a-card>
  <!--  添加和修改对话框-->
  <a-modal :title="`${formData.id?'编辑':'新增'}品牌`" :visible="modalVisible" @cancel="onClose" @ok="handleOk">

    <a-form ref="formRef" :label-col="labelCol" :model="formData" :rules="rules" :wrapper-col="wrapperCol">
      <a-form-item label="品牌名称" name="brandName">
        <a-input v-model:value="formData.brandName" placeholder="请输入品牌名称"/>
      </a-form-item>
      <a-form-item label="图片">
        <FileUpload
            :defaultFileList="defaultImgList.arr"
            :folder="FILE_FOLDER_TYPE_ENUM.BRAND.value"
            :maxUploadSize="1"
            :multiple="true"
            buttonText="点击上传图片"
            list-type="picture-card"
            @change="imgChange"
        />
      </a-form-item>
    </a-form>
  </a-modal>

</template>


<script setup>
import {defaultTimeRanges} from "/@/lib/default-time-ranges";
import {PAGE_SIZE, PAGE_SIZE_OPTIONS} from "/@/constants/common-const";
import {nextTick, onMounted, reactive, ref} from "vue";
import {smartSentry} from "/@/lib/smart-sentry";
import {TABLE_ID_CONST} from "/@/constants/support/table-id-const";
import TableOperator from "/@/components/support/table-operator/index.vue";
import {brandApi} from './brand-api';
import {message, Modal} from "ant-design-vue";
import {SmartLoading} from '/@/components/framework/smart-loading';
import _ from 'lodash';
import {FILE_FOLDER_TYPE_ENUM} from "/@/constants/support/file-const";
import FileUpload from "/@/components/support/file-upload/index.vue";
import {useRouter} from 'vue-router';


const router = useRouter();


const labelCol = {style: {width: '150px'}};
const wrapperCol = {span: 14};
const rules = {
  brandName: [{required: true, message: '品牌名称不能为空'}],
};
const formDataDefault = {
  id: undefined,
  brandName: undefined, //品牌名称
  icon: undefined,
};
let defaultImgList = reactive({arr: []});
let formData = reactive({...formDataDefault});
// 组件ref
const formRef = ref();

const columns = ref([
  {
    align: 'center',
    title: '品牌id',
    dataIndex: 'id',
    width: 60,
  },
  {
    align: 'center',
    title: '品牌名称',
    dataIndex: 'brandName',
    width: 80,
  },
  {
    align: 'center',
    title: '图标',
    dataIndex: 'icon',
    width: 80,
  },
  {
    align: 'center',
    title: '型号',
    dataIndex: 'modelCount',
    width: 80,
  },
  {
    align: 'center',
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 100,
  },
  {
    align: 'center',
    title: '操作',
    dataIndex: 'operate',
    width: 80,
    fixed: 'right'
  },
]);
const queryFormDataDefault = {
  updateTimeBegin: undefined, //修改时间 开始
  updateTimeEnd: undefined, //修改时间 结束
  brandName: undefined, //品牌名称
  pageNum: 1,
  pageSize: PAGE_SIZE,
};
const queryForm = reactive({...queryFormDataDefault});
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref();
// 日期选择
let searchDate = ref();
const modalVisible = ref(false);

function dateChange(dates, dateStrings) {
  queryForm.updateTimeBegin = dateStrings[0];
  queryForm.updateTimeEnd = dateStrings[1];
}

// 重置查询条件
function resetQuery() {
  searchDate.value = [];
  Object.assign(queryForm, queryFormDataDefault);
  ajaxQuery();
}

onMounted(() => {
  ajaxQuery();
});

function resetPageNumAjaxQuery(){
  queryForm.pageNum = 1;
  ajaxQuery();
}
// 查询
async function ajaxQuery(resetPageNum=false) {
  try {
    tableLoading.value = true;
    let responseModel = await brandApi.queryPage(queryForm);
    const list = responseModel.data.list;
    total.value = responseModel.data.total;
    tableData.value = list;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

// 图片改变
function imgChange(e) {
  console.log(e[0])
  formData.icon = e[0]?.url || '';
}

// 添加
function add() {
  showModal();
}

// 修改
function update(record) {
  Object.assign(formData, {
    id: record.id,
    brandName: record.brandName, //品牌名称
    icon: record.icon,
  });
  const imgType = record.icon ? record.icon.split('_') : '';
  defaultImgList.arr = record.icon ? [{fileUrl: record.icon, fileType: imgType[imgType.length - 1]}] : [];
  showModal();
}

const showModal = () => {
  modalVisible.value = true;
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

const handleOk = (e) => {
  save();
};

async function save() {
  formRef.value
      .validate()
      .then(async () => {
        SmartLoading.show();
        const form = _.cloneDeep(formData)
        try {
          if (form.id) {
            await brandApi.update(form);
          } else {
            await brandApi.add(form);
          }
          message.success(`${form.id ? '修改' : '添加'}成功`);
          ajaxQuery();
          onClose();
        } catch (error) {
          smartSentry.captureError(error);
        } finally {
          SmartLoading.hide();
        }
      })
      .catch((error) => {
        console.log('error', error);
        message.error('参数验证错误，请仔细填写表单数据!');
      });
}

function onClose() {
  Object.assign(formData, formDataDefault);
  defaultImgList.arr = [];
  modalVisible.value = false;
}

// 删除
function confirmDelete(record) {

  Modal.confirm({
    title: '提示',
    content: '确定要删除【' + record.brandName + '】吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      singleDelete(record);
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

async function singleDelete(brandData) {
  try {
    SmartLoading.show();
    await brandApi.delete(brandData.id);
    message.success('删除成功');
    ajaxQuery();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

function goToModelList(brandId) {
  router.push({path: '/data-config/model/model-list', query: {brandId}});
}

</script>

<style lang="less" scoped>

</style>